# -*- coding: utf-8 -*-

import json

from django.views.decorators.http import require_POST, require_GET

from common.chase import db as chase_db
from common.chase import handler as chase_handler
from common.chase.model import CHASE_ORDER_STATUS
from common.chase.model import CHASE_ORIGIN_TYPE
from common.console import db as user_db
from common.mch import db as mch_db
from common.mch.model import MCH_TYPE
from common.recharge import db as recharge_db
from common.recharge.model import RECHARGE_ORDER_STATUS
from common.utils import track_logging
from common.utils.api import token_required
from common.utils.decorator import response_wrapper, safe_wrapper
from common.utils.exceptions import ParamError
from common.utils.tz import utc_to_local_str
from common.withdraw import db as withdraw_db
from common.withdraw.model import WITHDRAW_ORDER_STATUS

_LOGGER = track_logging.getLogger(__name__)


@require_GET
@token_required
@response_wrapper
def get_order_list(req):
    query_dct = req.GET.dict()
    mch_dct = mch_db.get_mch_dct()
    cond = user_db.get_mchids_filter_by_user(req.user_id)
    if cond and query_dct.get('mch_id') is None:
        query_dct['mch_id'] = cond
    items, total_count, total_amount = chase_db.list_order(query_dct)
    resp_items = []
    for item in items:
        data = item.as_dict()
        data['created_at'] = utc_to_local_str(data['created_at'])
        data['updated_at'] = utc_to_local_str(data['updated_at'])
        data['mch_id'] = mch_dct[data['mch_id']]
        data['id'] = str(data['id'])
        resp_items.append(data)
    return {
        'list': resp_items,
        'page': query_dct.get('$page', 1),
        'total_amount': str(total_amount) if total_amount else '0',
        'size': len(resp_items),
        'total_count': total_count
    }


@require_POST
@token_required
@response_wrapper
@safe_wrapper
def create_order(req):
    params = json.loads(req.body)

    _LOGGER.info('create chase request: %s' % params)
    params['admin'] = req.user.username
    chase_origin_type = params['chase_origin_type']
    chase_origin_id = params['chase_origin_id']
    amount = float(params['amount'])

    # 只有已完成的原始订单可以追分
    if chase_origin_type == CHASE_ORIGIN_TYPE.RECHARGE:
        origin_order = recharge_db.get_order(chase_origin_id)
        if not origin_order or origin_order.status not in \
                [RECHARGE_ORDER_STATUS.DONE, RECHARGE_ORDER_STATUS.REJECTED]:
            raise ParamError('chase this order not allowed')
        if amount > float(origin_order.amount):
            raise ParamError(u'追分金额不能超过原始金额')

    elif chase_origin_type == CHASE_ORIGIN_TYPE.WITHDRAW:
        origin_order = withdraw_db.get_order(chase_origin_id)
        if not origin_order or origin_order.status not in [WITHDRAW_ORDER_STATUS.DONE, WITHDRAW_ORDER_STATUS.REJECTED]:
            raise ParamError('chase this order not allowed')
        if amount > float(origin_order.amount):
            raise ParamError(u'追分金额不能超过原始金额')

    if params.get('mch_id'):
        params['mch_id'] = mch_db.get_mch_info_by_name(params['mch_id'])['id']

    chase_order = chase_db.create_order(params)
    params['chase_id'] = chase_order.id

    mch_id = int(params["mch_id"])
    if mch_id in (MCH_TYPE.LOKI, MCH_TYPE.WITCH,):
        chase_handler.create_chase_order(params)

    chase_db.update_order(chase_order.id, CHASE_ORDER_STATUS.PROCESSED)

    return {
        'order_id': chase_order.id,
        'order_status': chase_order.status
    }
